<?php

namespace App\Morefun\Publishing;

use App\Entities\Activity;
use App\Entities\ActivityPublishing;
use Illuminate\Container\Container;
use Illuminate\Support\Arr;

class Publisher
{
    protected $defaultSchema = [
        'app' => [
            'is_open' => 'off',
            'app_urls' => [],
        ],
        'wechat' => [
            'is_open' => 'off',
            'qr_code' => [],
        ],
    ];

    public function publish($activityId, array $ways)
    {
        $format = [
            'app' => [
                'is_open' => Arr::get($ways, 'app.is_open', 'off'),
                'app_urls' => Arr::get($ways, 'app.app_urls', []),
            ],
            'wechat' => [
                'is_open' => Arr::get($ways, 'wechat.is_open', 'off'),
                'qr_code' => Arr::get($ways, 'wechat.qr_code', []),
            ],
        ];
        return Activity::query()->where('id', $activityId)
            ->update(['publishing_ways' => json_encode($format)]);
    }

    public function formatActivityPublishing($activityId)
    {
        $ways = Activity::query()->where('id', $activityId)->value('publishing_ways');
        $ways = json_decode($ways, true);

        return [
            'app' => [
                'is_open' => Arr::get($ways, 'app.is_open', 'off'),
                'app_urls' => Arr::get($ways, 'app.app_urls', []),
            ],
            'wechat' => [
                'is_open' => Arr::get($ways, 'wechat.is_open', 'off'),
                'qr_code' => Arr::get($ways, 'wechat.qr_code', []),
            ]
        ];
    }

    public function formatJsonString($raw)
    {
        if (empty($raw)) {
            return $this->defaultSchema;
        }

        return \GuzzleHttp\json_decode($raw, true);
    }
}
